package top.lunarye.handler.handler;

import top.lunarye.common.domaim.TaskInfo;
import top.lunarye.handler.flowControl.FlowControlParam;
import top.lunarye.handler.flowControl.FlowControlService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 各个渠道的基础handler
 * @author lunar
 * @since 2022-07-21
 */
public abstract class BaseHandler implements Handler {

    @Resource
    private HandlerHolder handlerHolder;

    @Resource
    private FlowControlService flowControlService;

    /**
     * 表示渠道的code
     * 子类初始化的时候指定
     */
    protected Integer channelCode;

    /**
     * 限流相关的参数
     * 子类初始化时进行指定
     */
    protected FlowControlParam flowControlParam;

    /**
     * 填充handlerHolder
     */
    @PostConstruct
    public void init() {
        handlerHolder.putHandler(channelCode, this);
    }

    /**
     * 单机流量控制
     * @param taskInfo
     */
    public void flowControl(TaskInfo taskInfo) {
        if (flowControlParam != null) {
            flowControlService.flowControl(taskInfo, flowControlParam);
        }
    }

    @Override
    public void doHandler(TaskInfo taskInfo) {
        flowControl(taskInfo);
        handler(taskInfo);
    }

    /**
     * handler具体处理taskInfo函数
     * @param taskInfo
     * @return
     */
    public abstract boolean handler(TaskInfo taskInfo);
}
